
import {createRouter, createWebHistory} from 'vue-router'
import store from "@/store";



const routes = [
  // {
  //   path: '/',
  //   name:"Manage",
  //   component: () => import('../views/Manage.vue'),
  //   redirect: "/home",
  //   children: [
  //     { path: 'person', name: 'Person', component: () => import('../views/Person.vue')},
  //   ]
  // },
  {
    path:'/login',
    name:'Login',
    component: () => import('../views/Login.vue'),
  },
  {
    path:'/register',
    name:'Register',
    component: () => import('../views/Register.vue'),
  },
  {
    path:'/test',
    name:'Test',
    component: () => import('../views/test.vue'),
  },
  {
    path:'/404',
    name:'NotFound',
    component: () => import('../views/404.vue'),
  },
  {
    path: "/:catchAll(.*)", // 不识别的path自动匹配404
    redirect: '/404',
  },
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// export const resetRouter=()=>{
//   router.=createRouter({
//     history: createWebHistory(),
//     routes
//   })
// }
export function resetRouter() {
  const newRouter = createRouter();
  router.matcher = newRouter.matcher;
}

//注意：刷新页面会导致路由重置
export const setRoutes=()=>{
  const storeMenu=localStorage.getItem("menus");
  if(storeMenu){
    const manageRoute={path:'/',name:'manage', component:()=>import('../views/Manage.vue'),redirect:"/login",children:[
        //静态路由
        {path: 'person', name: 'Person', component: () => import('../views/Person.vue')}
      ]}
    const menus=JSON.parse(storeMenu)
    menus.forEach(item=>{
      if(item.path){
        let itemMenu={path: item.path.replace("/",""),name:item.name,component:()=>import('../views/'+item.pagePath+'.vue')}
        manageRoute.children.push(itemMenu)
      }else if(item.children.length){
        item.children.forEach(item=>{
          if(item.path){
            let itemMenu={path: item.path.replace("/",""),name:item.name,component:()=>import('../views/'+item.pagePath+'.vue')}
            manageRoute.children.push(itemMenu)
          }
        })
      }
    })
    const currentRoutesName=router.getRoutes().map(v=>v.name)
    if(!currentRoutesName.includes('manage')){
      router.addRoute(manageRoute)
    }
  }
}

//重置就在set一次
setRoutes()


// router.beforeEach((to,from,next)=>{
//

// })
router.beforeEach((to, from, next) => {
  localStorage.setItem("currentPathName", to.name)  // 设置当前的路由名称，为了在Header组件中去使用
  store.commit("setPath")  // 触发store的数据更新
  next()  // 放行路由

  if (!to.matched.length){
    const storeMenus = localStorage.getItem("menus")
    if(storeMenus){
      next("/404")
    }else{
      next("/login")
    }
  }
  next()
})

export default router